﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using BLL;
using System.Collections;
using Entity;
using System.Data.SqlClient;
using System.Web.Services;
using DbCommon;

namespace Web.admin.students
{
    public partial class show : System.Web.UI.Page
    {
        static DataTable table;
        static int ItemCount;//总条数
        static int PageCount;//总页数
        static int PageIndex;//当前页
        static int PageSize = 20;//分页数据长度
        DbHelper dbhelper = new DbHelper();

        StudentService studentservice = new StudentService();
        ClassService classes = new ClassService();
        AcademyService academyService = new AcademyService();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Session["classesCon"] = "";
                Session["AcademyCon"] = "";
                //每次第一次加载的时候就将当前页置为1
                PageIndex = 1;
                ItemCount = dbhelper.GetCount("Students");
                //总页数
                PageCount = (ItemCount + PageSize - 1) / PageSize;
                for (int i = 1; i <= PageCount; i++)
                {
                    DDLPager.Items.Add(new ListItem("第" + i.ToString() + "页", i.ToString()));
                }
                AcademyBind();
                ClassesBind("==所有班级==", ddl_classes);
                ClassesBind("",ddl_Class_add);
                ClassesBind("", ddl_students_edit);
                StudentsDataBind();
            }
        }

        /// <summary>
        /// 对学院的绑定
        /// </summary>
        protected void AcademyBind()
        {
            ddl_academy.DataValueField = "ACA_ID";
            ddl_academy.DataTextField = "ACA_NAME";
            ddl_academy.DataSource = academyService.getAllAcademies();
            ddl_academy.DataBind();
        }

        /// <summary>
        /// 数据绑定
        /// </summary>
        protected void StudentsDataBind()
        {
            //两个if语句用来处理下一页或者上一页的刷新效果
            if (PageIndex > PageCount)
                PageIndex = PageCount;
            else if (PageIndex < 1)
                PageIndex = 1;
            //开始条数
            int StartItem;
            //结束条数
            int EndItem;
            //开始页码所要获得的条数
            StartItem = PageSize * (PageIndex - 1);
            //条件选择是否超过总的条数
            EndItem = ItemCount > StartItem + PageSize ? StartItem + PageSize : ItemCount;
            if (Session["OrderCon"] == null || Session["OrderCon"].ToString() == "")
                Session["OrderCon"] = "STU_NAME desc";
            Session["SelectCon"] =" 1=1 "+ Session["classesCon"].ToString() + Session["AcademyCon"].ToString();
            if (Session["SelectCon"] != null && Session["SelectCon"].ToString() != "")
            {
                if (!string.IsNullOrEmpty(Request.QueryString["select"]))
                {
                    string ddlselect = Request.QueryString["select"];
                    ddl_classes.SelectedValue = ddlselect;
                    Session["SelectCon"] += " and STU_CLASSES = '" + ddlselect + "'";
                }
                table = dbhelper.GetPageTable("v_Students", StartItem, EndItem, Session["OrderCon"].ToString(), Session["SelectCon"].ToString());
            }
            else
                table = dbhelper.GetPageTable("v_Students", StartItem, EndItem, Session["OrderCon"].ToString(), "");
            BindPage();
        }


        /// <summary>
        /// page控件绑定
        /// </summary>
        protected void BindPage()
        {
            //绑定当前的前台
            //当前总的页数
            lbPageAll.InnerText = ItemCount.ToString();
            lbPager.InnerText = PageCount.ToString();
            lbIndexPage.InnerText = PageIndex.ToString();
            DDLPager.SelectedValue = PageIndex.ToString();
            if (PageIndex <= 1)
            {
                First.Enabled = false;
                Prev.Enabled = false;
            }
            else
            {
                First.Enabled = true;
                Prev.Enabled = true;
            }
            if (PageIndex >= PageCount)
            {
                Next.Enabled = false;
                Last.Enabled = false;
            }
            else
            {
                Next.Enabled = true;
                Last.Enabled = true;
            }
            RP_Bind();
        }

        /// <summary>
        /// 根据表格得到相应的列表
        /// </summary>
        /// <returns></returns>
        protected void RP_Bind()
        {
            RpList.DataSource = table;
            RpList.DataBind();
        }
        /// <summary>
        /// 对DropDownList的绑定
        /// </summary>
        /// <param name="firstStr">第一行显示的数据</param>
        /// <param name="ddl">DropDownList控件</param>
        protected void ClassesBind(string firstStr, DropDownList ddl)
        {
            ddl.Items.Clear();

            if (!string.IsNullOrEmpty(firstStr))
            {
                ddl.Items.Add(new ListItem(firstStr, ""));
            }
            List<BoClasses> boacademy = classes.GetAllClasses(null);
            if (boacademy!=null)
            {
                foreach (BoClasses aca in boacademy)
                {
                    ddl.Items.Add(new ListItem(aca.CLA_NAME, aca.CLA_ID));
                }
            }
        }

        /// <summary>
        /// 排序列表文本改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlorderChange(object sender, EventArgs e)
        {
            Session["OrderCon"] = ddlorder.SelectedValue;
            StudentsDataBind();
        }
        /// <summary>
        /// 班级列表文本改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddl_classesChange(object sender,EventArgs e)
        {

            if (!string.IsNullOrEmpty(ddl_classes.SelectedValue))
            {
                Session["classesCon"] = " and STU_CLASSES = '" + ddl_classes.SelectedValue + "'";
            }
            else
                Session["classesCon"] = "";
            PageBind();
            StudentsDataBind();
        }
        /// <summary>
        /// 搜索事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSearchClick(object sender,EventArgs e)
        {
            string txt = txtKeywords.Text;
            Response.Redirect("STU_SelList.aspx?searchCon=" + ddlSerch.SelectedValue + "&searchTxt=" + txt);
        }
        /// <summary>
        /// 批量删除事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void BatchDelete(object sender, EventArgs e)
        {
            ArrayList StudentsId = new ArrayList();
            for (int i = 0; i < RpList.Items.Count; i++)
            {
                string id = ((HiddenField)RpList.Items[i].FindControl("hf_StudentId")).Value;
                CheckBox cb = (CheckBox)RpList.Items[i].FindControl("CbChoose");
                if (cb.Checked)
                {
                    StudentsId.Add(id);
                }
            }
            int result = studentservice.DleteMoreStudents(StudentsId);
            Response.Write("<script>alert('删除成功，共删除" + result + "条数据');window.location.href='STU_List.aspx'; </script>");
            return;
        }
        /// <summary>
        /// 添加学生事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void AddStudent(object sender, EventArgs e)
        {
            BoStudents bostudents = new BoStudents();
            bostudents.STU_CLASSES = ddl_Class_add.SelectedValue;
            bostudents.STU_CODE = txt_studentCode_add.Value;
            bostudents.STU_NAME = txt_studentName_add.Value;
            bostudents.STU_USERNAME = txt_studentUsm_add.Value;
            bostudents.STU_PASSWORD = txt_studentPwd_add.Value;
            if (rd_female_add.Checked)
                bostudents.STU_GENDER = "0";
            else if (rd_male_add.Checked)
                bostudents.STU_GENDER = "1";
            if (!string.IsNullOrEmpty(txt_studentGrade_add.Value))
                bostudents.STU_GRADE = txt_studentGrade_add.Value;
            else
            {
                Response.Write("<script>alert('输入的年级有误，请检查格式')</script>");
                return;
            }
            studentservice.CreateStudent(bostudents);
            Response.Write("<script>alert('添加成功');window.location.href='STU_List.aspx?select=" + bostudents.STU_CLASSES + "'; </script>");
        }
        /// <summary>
        /// 修改学生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /*protected void EditStudent(object sender, EventArgs e)
        {
            BoStudents studentModel = new BoStudents();
            studentModel.STU_CLASSES = ddl_students_edit.SelectedValue;
            studentModel.STU_CODE = txt_studentCode_edit.Value;
            if (rd_male_edit.Checked)
                studentModel.STU_GENDER = "1";
            else if (rd_female_edit.Checked)
                studentModel.STU_GENDER = "0";
            if (!string.IsNullOrEmpty(txt_studentGrade_edit.Value))
                studentModel.STU_GRADE = txt_studentGrade_edit.Value;
            studentModel.STU_ID = stu_Id.Value;
            studentModel.STU_NAME = txt_studentName_edit.Value;
            studentModel.STU_PASSWORD = txt_studentPwd_edit.Value;
            studentModel.STU_USERNAME = txt_studentUsm_edit.Value;
            studentservice.UpdateStudent(studentModel);
            Response.Write("<script>alert('修改成功');window.location.href='STU_List.aspx?select=" + studentModel.STU_CLASSES+ "';</script>");
        }*/

        [WebMethod]
     /*   public static string delStudent(string studentId)
        {
            if (!string.IsNullOrEmpty(studentId))
            {
                BLL.StudentService studentservice = new BLL.StudentService();
                studentservice.DeleteStudent(studentId);
                return "{'resultjson':'1'}";
            }
            else
                return "{'resultjson':'0'}";
        }*/
        protected void RpOperate(object sender, RepeaterCommandEventArgs e)
        {
            string studentId = ((HiddenField)e.Item.FindControl("hf_StudentId")).Value;
            switch (e.CommandName)
            {
                case "delStudent":
                    studentservice.DeleteStudent(studentId);
                    break;
            }
            Response.Redirect("STU_List.aspx");
            
        }
        /// <summary>
        /// 学院改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddl_academy_SelectedIndexChanged(object sender, EventArgs e)
        {
            Session["classesCon"] = "";
            if (ddl_academy.SelectedValue == "")
            {
                ClassesBind("==所有班级==", ddl_classes);
                Session["AcademyCon"] = "";
            }
            else
            {
                ddl_classes.Items.Clear();
                IList<BoClasses> boclasses = classes.getClassesByAcademy(ddl_academy.SelectedValue);
                ddl_classes.Items.Add(new ListItem("全部班级", ""));
                if (boclasses != null)
                {
                    foreach (BoClasses aca in boclasses)
                    {
                        ddl_classes.Items.Add(new ListItem(aca.CLA_NAME, aca.CLA_ID));
                    }
                    ddl_classes.SelectedIndex = 0;
                    Session["AcademyCon"] = " and ACA_ID='" + ddl_academy.SelectedValue + "'";
                }
            }
            PageBind();
            StudentsDataBind();
        }
        /// <summary>
        /// 页码绑定
        /// </summary>
        protected void PageBind()
        { 
            Session["SelectCon"] =" 1=1 "+ Session["classesCon"].ToString() + Session["AcademyCon"].ToString();
            //每次第一次加载的时候就将当前页置为1
            PageIndex = 1;
            ItemCount = dbhelper.GetCount("v_Students", Session["SelectCon"].ToString());
            //总页数
            PageCount = (ItemCount + PageSize - 1) / PageSize;
            DDLPager.Items.Clear();
            for (int i = 1; i <= PageCount; i++)
            {
                DDLPager.Items.Add(new ListItem("第" + i.ToString() + "页", i.ToString()));
            }
        }

        /// <summary>
        /// 页码点击事件
        /// </summary>
        /// <param name="sender">对象</param>
        /// <param name="e">事件</param>
        protected void PageClick(object sender, EventArgs e)
        {
            //当前页码
            int iCurrentPageIndex = PageIndex;
            //页码总数
            int iPageCount = PageCount;
            string sCommandName = (sender as LinkButton).CommandName;
            switch (sCommandName)
            {
                case "First":
                    PageIndex = 1;
                    break;
                case "Last":
                    PageIndex = iPageCount;
                    break;
                case "Prev":
                    PageIndex = iCurrentPageIndex - 1;
                    break;
                case "Next":
                    PageIndex = iCurrentPageIndex + 1;
                    break;
            }
            StudentsDataBind();

        }

        /// <summary>
        /// 页码下拉列表改变事件
        /// </summary>
        /// <param name="sneder">对象</param>
        /// <param name="e">事件</param>
        protected void DDLpager_Change(object sneder, EventArgs e)
        {
            PageIndex = Convert.ToInt32(DDLPager.SelectedValue);
            StudentsDataBind();
        }
    }
}